package com.ruoyi.framework.mqtt.handler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.project.instrument.domain.InsInstrument;
import com.ruoyi.project.system.service.ISysDictDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Component;

/**
 * @author Taney
 */
@Component
public class PropertiesReportHandler extends AbstractHandler {

    public static final String TOPIC = "/properties/report";
    //仪器在线状态
    public static final String NET_STATE_ONLINE = "2";
    public static final String DICTYPE_INSTRUMENT_STATE = "instrument_state";

    @Autowired
    ISysDictDataService iSysDictDataService;

    @Override
    public void handleMessage(Message message, String topic, String msg) throws MessagingException {
        if (matches(TOPIC, topic)) {
            if (msg != null) {
                ClientInfo clientInfo = getClientInfo(topic);
                String product = clientInfo.getProduct();
                String deviceId = clientInfo.getDeviceId();
                String stateDesc = iSysDictDataService.selectDictLabel(DICTYPE_INSTRUMENT_STATE, msg);
                logger.debug("设备[{}-{}]当前状态为【{}】", product, deviceId, stateDesc);
                QueryWrapper<InsInstrument> insInstrumentQueryWrapper = new QueryWrapper<>();
                insInstrumentQueryWrapper.eq("name", deviceId);
                InsInstrument instrument = insInstrumentService.getOne(insInstrumentQueryWrapper);
                if (instrument != null) {
                    instrument.setState(msg);
                    instrument.setNetState(NET_STATE_ONLINE);
                    insInstrumentService.update(instrument,insInstrumentQueryWrapper);
                }
            }
        }
    }
}
